package com.hqd.ch03.v17.utils;

import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;

/**
 * 泛型工具类
 */
public class GenericClassUtils {

    public static Class[] getInterfaceActualTypeArguments(Class<?> clazz, Class<?> targetInterface) {
        if (clazz == null || targetInterface == null) {
            return null;
        }
        ParameterizedType[] genericInterfaces = Arrays.stream(clazz.getGenericInterfaces())
                .filter(gi -> gi instanceof ParameterizedType)
                .toArray(ParameterizedType[]::new);
        if (ArrayUtils.isNotEmpty(genericInterfaces)) {
            for (ParameterizedType pt : genericInterfaces) {
                Type rawType = pt.getRawType();
                if (rawType == targetInterface) {
                    return Arrays.stream(pt.getActualTypeArguments()).toArray(Class[]::new);
                }

            }
        }
        return null;
    }

    public static Class<?> getInterfaceActualTypeArgument(Class<?> clazz, Class<?> targetInterface, int index) {
        if (index < 0) {
            return null;
        }
        Class[] typeArguments = getInterfaceActualTypeArguments(clazz, targetInterface);
        if (ArrayUtils.isNotEmpty(typeArguments)) {
            if (index >= typeArguments.length) {
                return null;
            }
            return typeArguments[index];
        }
        return null;
    }


}
